package cn.shop.dys.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.otto.Subscribe;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.shop.dys.R;
import cn.shop.dys.activity.UserIndentDetailActivity;
import cn.shop.dys.adapter.CommonIndentAdapter;
import cn.shop.dys.adapter.WaitEvaluateAdapter;
import cn.shop.dys.bean.AllIndentItem;
import cn.shop.dys.bean.CartItem;
import cn.shop.dys.bean.MyCheckoutAddup;
import cn.shop.dys.bean.OrderInfo;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.util.BusFactory;
import cn.shop.dys.util.SPUtil;
import cn.shop.lib_common.CommonUtil;


/**
 * 待评价
 * Created by sunjian on 2016/4/20.
 */
public class WaitEvaluateFragment extends IndentBaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    @ViewInject(R.id.rl_left)
    private View mLeft;
    @ViewInject(R.id.rl_center)
    private View mCenter;
    @ViewInject(R.id.rl_right)
    private View mRight;
    @ViewInject(R.id.lv_all_indent_list)
    private ListView mAllIndentList;
    @ViewInject(R.id.rl_all_indent_list_empty)
    private View mListEmpty;
    private WaitEvaluateAdapter mAdapter;

    @Override
    public int getStatus() {
        return CommonConstant.INDENT_TYPE_NOT_EVALUATE;
    }

    @Override
    public void initEvent() {
        mLeft.setOnClickListener(this);
        mCenter.setOnClickListener(this);
        mRight.setOnClickListener(this);
    }

    @Override
    public void initListView() {
        mAllIndentList.setEmptyView(mListEmpty);
        super.initListView();
    }

    @Override
    public void setAdapter() {
        if (mAdapter == null) {
            //  Log.d("test",mAllIndentItems.toString());
            mAdapter = new WaitEvaluateAdapter(mAllIndentItems, mContext, CommonConstant.INDENT_TYPE_NOT_EVALUATE);
            mAllIndentList.setAdapter(mAdapter);
            mAllIndentList.setOnItemClickListener(this);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }
    /*@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init() {
        initEvent();
        initListView();
    }

    private void initEvent() {
        mLeft.setOnClickListener(this);
        mCenter.setOnClickListener(this);
        mRight.setOnClickListener(this);
    }

    private void initListView() {
        mAllIndentList.setEmptyView(mListEmpty);
        initAllOrderInfo("0", "1");
        initAllOrderInfo("0", "2");
        initAllOrderInfo("0", "3");
    }

    private void setAdapter() {
        if (mAdapter == null) {
            //  Log.d("test",mAllIndentItems.toString());
            mAdapter = new WaitEvaluateAdapter(mAllIndentItems, mContext, CommonConstant.INDENT_TYPE_NOT_EVALUATE);
            mAllIndentList.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }*/

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_left:
                break;
            case R.id.rl_center:
                break;
            case R.id.rl_right:
                break;
        }
    }

   /* @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_all_indent, null);
    }

    private List<OrderInfo> mOrderInfos = new ArrayList<>();
    private List<AllIndentItem> mAllIndentItems = new ArrayList<>();

    private void initAllOrderInfo(final String page, final String type) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID));
        params.addBodyParameter("type", type);
        params.addBodyParameter("page", page);
        params.addBodyParameter("pageNum", "10");
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_ORDER_LIST, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("orderList")) {
                                    String orderList = jsonObject.getString("orderList");
                                    List<OrderInfo> orderInfos = mGson.fromJson(orderList,
                                            new TypeToken<List<OrderInfo>>() {
                                            }.getType());
                                    if (orderInfos.size() > 0) {
                                        mOrderInfos.addAll(orderInfos);
                                        for (OrderInfo orderInfo : orderInfos) {
                                            initAllDetailOrderInfo(orderInfo, page, type);
                                        }
                                        // TODO: 2016/4/22 考虑多个图片
                                        *//*if (mOrderInfos.size() % 10 == 0) {
                                            int myPage = Integer.parseInt(page) + 1;
                                            initAllOrderInfo(String.valueOf(myPage), type);
                                        } else {
                                            setAdapter();
                                        }*//*
                                    }
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(mContext, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(mContext, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(mContext, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(mContext, "网络未连接2" + msg);
                    }

                });
    }

    private void initAllDetailOrderInfo(OrderInfo orderInfo, final String page, final String type) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID));
        params.addBodyParameter("orderId", orderInfo.getOrderId());
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_ORDER_DETAIL, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("orderDetail")) {
                                    String orderInfoStr = jsonObject.getString("orderInfo");
                                    OrderInfo orderInfo = mGson.fromJson(orderInfoStr, OrderInfo.class);
                                    String productListStr = jsonObject.getString("productList");
                                    List<CartItem> cartItems = mGson.fromJson(productListStr,
                                            new TypeToken<List<CartItem>>() {
                                            }.getType());
                                    String checkoutAddup = jsonObject.getString("checkoutAddup");
                                    MyCheckoutAddup myCheckoutAddup = mGson.fromJson(checkoutAddup, MyCheckoutAddup.class);
                                    mAllIndentItems.add(new AllIndentItem(orderInfo, cartItems, myCheckoutAddup));
                                    if (mOrderInfos.size() % 10 == 0) {
                                        int myPage = Integer.parseInt(page) + 1;
                                        initAllOrderInfo(String.valueOf(myPage), type);
                                    } else {
                                        for (AllIndentItem mAllIndentItem : mAllIndentItems) {
                                            OrderInfo tOrderInfo = mAllIndentItem.getmOrderInfo();
                                            Log.d("test", "flag" + tOrderInfo.getFlag());
                                            if (tOrderInfo.getFlag() == 1 || tOrderInfo.getFlag() == 2) {
                                                mAllIndentItems.remove(mAllIndentItem);
                                            }
                                        }
                                        setAdapter();
                                    }
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(mContext, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(mContext, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(mContext, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(mContext, "网络未连接1" + msg);
                    }

                });
    }*/
   @Override
   public void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       BusFactory.getBus().register(this);
   }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }
    @Subscribe
    public void disposeData(AllIndentItem allIndentItem) {
        int flag = allIndentItem.getmOrderInfo().getFlag();
        String orderId = allIndentItem.getmOrderInfo().getOrderId();
        if(flag==3){
            List<AllIndentItem> infos=new ArrayList<>();
            infos.addAll(mAllIndentItems);
            for (AllIndentItem info : infos) {
                if(info.getmOrderInfo().getOrderId().equals(orderId)){
                    infos.remove(info);
                    break;
                }
            }
            mAdapter.setAllIndentItems(infos);
            mAllIndentItems=infos;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent=new Intent(mContext, UserIndentDetailActivity.class);
        CommonUtil.showToast(mContext, "mAllIndentItems" + mAllIndentItems.get(position).getmOrderInfo().getOrderId());
        intent.putExtra("orderId",mAllIndentItems.get(position).getmOrderInfo().getOrderId());
        //   mContext.startActivity(intent);
        startActivityForResult(intent,CommonConstant.QUERY_NOT_EVALUATE_INDENT_REQUEST_CODE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==CommonConstant.QUERY_NOT_EVALUATE_INDENT_REQUEST_CODE&&resultCode==CommonConstant.QUERY_INDENT_RESULT_CODE){
            String orderId = data.getStringExtra("orderId");
            if(!TextUtils.isEmpty(orderId)){
                List<AllIndentItem> infos = new ArrayList<>();
                infos.addAll(mAllIndentItems);
                for (AllIndentItem info : infos) {
                    if (info.getmOrderInfo().getOrderId().equals(orderId)) {
                        BusFactory.getBus().post(info);
                        infos.remove(info);
                        break;
                    }
                }
                mAdapter.setAllIndentItems(infos);
                mAllIndentItems = infos;
            }
        }
    }
}
